<template>
    <div id='myApp'>
        <Row style="margin-bottom: 10px;border-bottom: 1px solid #eeeeee;">
            <Col span="3" style="border-bottom:2px solid #2d8cf0 ;padding: 0 0 8px 18px;">
            <span style="color: #2d8cf0;">
                <Icon type="md-globe" />&nbsp;&nbsp;数据源管理</span>
            </Col>
            <Col span="5" offset="16">
                <div style="float:right">
                    <!-- <Button label="small" style="height: 27px;">
                        导出<Icon type="md-download"></Icon>
                    </Button> -->
                    <Button @click="openmodal" type="success" label="small"
                    style="border: none;height: 27px; ">创建数据源</Button>
                </div>
            </Col>
            <Modal v-model="modal1" width="700">
                <p slot="header" style="color: #2d8cf0;">                    
                    <Icon type="ios-information-circle"></Icon>
                    <span v-if="modaltype==1">
                        创建数据源
                    </span>
                    <span v-else-if="modaltype==2">
                        查看详情
                    </span>
                    <span v-else>
                        修改数据源
                    </span>
                </p>
                <div>
                    <Form ref="ruleForm" :rules="ruleValidate" :model="ruleForm" label-position="right" :label-width="120">
                        <FormItem prop="name" label="数据源名称：">
                            <Input v-model="ruleForm.name" :disabled="onlyEdit" />
                        </FormItem>

                        <FormItem label="类型：">
                            <Select v-model="ruleForm.type" :disabled="onlyView" @on-change="viewtypeList" placeholder=''>
                                <Option v-for="item in typeDatasource" :value="item.value" :key="item.value">
                                {{item.label}}
                                </Option>
                            </Select>
                        </FormItem>
                        <FormItem prop="config" label="配置：">
                            <!-- <Input type="textarea" :autosize="{minRows: 5,maxRows: 10}" :disabled="onlyView" v-model="ruleForm.config" /> -->
                            <vue-json-editor 
                            v-model="ruleFormconfig" 
                            :mode="'code'" 
                            lang="zh"
                            @json-change="onJsonChange"
                            @has-error="onError"
                            >    
                            </vue-json-editor>
                        </FormItem>
                        <!-- <div class="dast_form_items dast_form_itemsub">
                            <div class="sublabel">配置：</div>
                            <div class="items_input">
                                <Input type="textarea" :autosize="{minRows: 5,maxRows: 10}" :disabled="onlyView" v-model="ruleFormconfig" />
                            </div>
                        </div> -->
                        <div class="dast_form_items dast_form_itemsub">
                            <div class="sublabel">状态：</div>
                            <div class="items_input">
                                <i-switch :disabled="onlyView" v-model="ruleForm.enabled" @on-change="changestatus" />
                            </div>
                        </div>                        
                    </Form>
                </div>
                <div slot="footer">
                	<template v-if="modaltype==2">
                    	<Button type="primary" @click="asyncOK">确定</Button>
                    </template>
                    <template v-else>
                        <Button type="primary" @click="saveStorage">保存</Button>                    	
                    </template>
                </div>
            </Modal>
        </Row>
        <!--
        <Row style="margin-bottom: 20px;">
            <Col span="8">
            <Input style="width:95%" placeholder="请输入标题名称进行模糊查询" />
            </Col>
            <Col span="2">

            <Button type="primary" @click="search">
                <Icon type="ios-search" />
            </Button>
            </Col>
            <Col span="6" offset="8">
            
            <div style="float: right;">
                <Button type="text" @click="search" style="color: #2d8cf0;">
                    高级搜索
                </Button>
                <Button @click="search">
                    导出<Icon type="md-download"></Icon>
                </Button>
            </div>
            </Col>
            
        </Row>
        -->

        <Table :columns="httpColumns" :data="httpData"></Table>
        <div style="float: right; margin-top: 15px">
            共{{dataCount}}条
        </div>

    </div>
    </div>
</template>
<style type="text/css">
.ivu-modal div.jsoneditor-menu{display:none!important;}
</style>
<style type="text/css" scoped>
.dast_form_items{
    display: flex;
    -webkit-display:flex;
    flex-flow: row;
    -webkit-flex-flow: row;    
}
.dast_form_items .items_label{
    margin:5px 0 0 0;
    text-align: left;
}
.dast_form_items .items_input{
    flex:1;
    -webkit-flex:1;
}
.dast_form_items .sublabel{
    width:100px;
    text-align: right;
    padding: 0 12px 0 0;
    box-sizing: border-box;
}
.dast_form_itemsub{
   align-items: center;
   -webkit-align-items: center;
   margin-bottom: 24px;
}
</style>
<script>
import zmitiUtil from '../lib/util'
import { mapState, mapActions } from 'vuex'
import vueJsonEditor from 'vue-json-editor'
    export default {
        computed:{
            codemirror() {
                return this.$refs.myCm.codemirror
            },
            ... mapState({
                Authorization: state => state.Authorization
            })
        },
        components:{
            vueJsonEditor
        },
        data() {
            const validateConfig = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('请输入配置'));
                }
                // 异步验证
                setTimeout(() => {
                    var path='storage/verifyConfig';
                    var postData = {
                        config:value
                    };
                    zmitiUtil.Ajax(path,postData).then(res => {                        
                        if(res.data.code!=1){
                            callback(new Error(res.data.result));
                        }else{                            
                            callback();
                        }
                        
                    }).catch((error) => {
                        console.log(error,'error');
                    });

                }, 1000);
            };
            return {
                json: {
                    msg: 'demo of jsoneditor'
                },
                typeDatasource:[{
                    label:'file',
                    value:'file'
                },{
                    label:'jdbc',
                    value:'jdbc'
                },{
                    label:'mongo',
                    value:'mongo'
                },{
                    label:'hbase',
                    value:'hbase'
                },{
                    label:'hive',
                    value:'hive'
                },{
                    label:'kafka',
                    value:'kafka'
                },{
                    label:'kudu',
                    value:'kudu'
                },{
                    label:'s3',
                    value:'s3'
                },{
                    label:'openTSDB',
                    value:'openTSDB'
                }],
                modaltype:1,//1添加，2查看，3修改
                modaltypetext:['创建数据源','查看详情','修改数据源'],
                onlyView:false,
                onlyEdit:false,
                ruleForm: {
                    name: '',
                    type:'',
                    enabled:true,
                    config: ''
                },
                ruleFormconfig:'',
                ruleFormtype:'',
                enabled:true,
                currentIndex:-1,
                cmOptions:{
                    value:'',
                    mode: 'application/json',
                    indentWithTabs: true,
                    smartIndent: true,
                    lineNumbers: true,
                    matchBrackets: true,
                    extraKeys:{
                        "F7": function autoFormat(editor) {
                            console.log(editor,'editor-F7')
                            var totalLines = editor.lineCount();
                            editor.autoFormatRange({line:0, ch:0}, {line:totalLines});
                        }//代码格式化
                    },
                },
                ruleValidate: {
                    name: [{
                        required: true,
                        message: "请输入数据源名称",
                        trigger: "blur"
                    }],
                    config: [{
                        validator: validateConfig,
                        required: true,
                        trigger: "blur"
                    }],
                },
                modal1: false,
                dataCount: 0,
                pageSize: 1000,
                ajaxHttpData: [],
                xia: 0,
                httpColumns: [
                    {
                        title: '编号',
                        width: 80,
                        key: 'num',
                        align: 'center',
                        render:(h,params)=>{
                            let indexnum=params.row._index+1
                            return h('div',{},indexnum)
                        }
                    },
                    {
                        title: '名称',
                        key: 'name',
                        align: 'center'
                    },
                    {
                        title: '类型',
                        key: 'type',
                        align: 'center',
                        width:150,
                        render: (h, params) => {                            
                            return h('p', {}, params.row.config.type)
                        }
                    },
                    {
                        title: '状态',
                        key: 'enabled',
                        align: 'center',
                        width:100,
                        render: (h, params) => {
                            const row = params.row.config;
                            const text = row.enabled == true ? '正常' : '已停用';
                            const color = row.enabled == true ? '#19be6b' : '#ed4014';
                            return h('div', [
                                h('p', {
                                    style: {
                                        color: color
                                    }
                                }, text)
                            ]);
                        }
                    },
                    {
                        title: '操作',
                        key: 'operate',
                        width: 240,
                        align: 'center',
                        render: (h, params) => {
                            const row = params.row;
                            const text = row.config.enabled == true ? '停用' : '启用';
                            return h('div', [
                                h('Button', {
                                    props: {
                                        size: 'small',
                                        type: 'text'
                                    },
                                    style: {
                                        marginRight: '5px',
                                        color:'#2d8cf0'
                                    },
                                    on: {
                                        click: () => {
                                            this.onlyView=false;
                                            this.onlyEdit=true;
                                            this.modaltype=3;
                                            this.openDetail(params.row.name,0)
                                        }
                                    }
                                }, '修改'),
                                h('Tooltip', {
                                    props: {
                                        placement: 'top',
                                        content: '停用/启用'
                                    }
                                }, [
                                    h('Button', {
                                        props: {
                                            size: 'small',
                                            type:'text'
                                        },
                                        style: {
                                            marginRight: '5px',
                                            color:'#2d8cf0'
                                        },
                                        on: {
                                            click: () => {
                                                //停用启用操作
                                                let enabled=!params.row.config.enabled;
                                                this.checkStorage(params,enabled)

                                            }
                                        }
                                    }, text)
                                ]),

                                h('Button', {
                                    props: {
                                        size: 'small',
                                        type: 'text'
                                    },
                                    style: {
                                        marginRight: '5px',
                                        color:'#2d8cf0'
                                    },
                                    on: {
                                        click: () => {
                                            this.onlyView=true;
                                            this.onlyEdit=true;
                                            this.modaltype=2;
                                            this.openDetail(params.row.name,0)
                                        }
                                    }
                                }, '查看'),
                                h('Poptip', {
                                          props: {
                                              confirm: true,
                                              type: 'error',
                                              size: 'large',
                                              title: '你确定要删除吗?',
                                              transfer:true
                                          }, 
                                          on: {
                                              'on-ok': () => {
                                                  this.delStorage(params.row.name);
                                              }
                                          }
                                      }, [
                                          h('Button', {
                                              props: {
                                                  type: 'text',
                                                  size: 'small'                                                 
                                              },
                                              style: {
                                                  marginRight: '5px',
                                                  color:'#2d8cf0'
                                              },
                                          },'删除')
                              ])
                            ]);
                        }
                    }

                ],
                httpData: []
            }
        },
        mounted() {             
            this.getDatalist();
            //this.tetstList();
        },
        methods: {
            onJsonChange (value) {//json编辑器内容有更改时
                console.log('更改后的json:', value);
                this.ruleForm.config=JSON.stringify(value);
            },
            onError (value) {//json编辑器内容有错误时
                console.log('value:', value);
            },
            changestatus(status){
                this.ruleForm.enabled=status;                
                console.log(status,'status');
            },
            openmodal(){
                this.modal1=true;
                this.modaltype=1;
                this.onlyView=false;
                this.onlyEdit=false;
                this.ruleForm= {
                    name: '',
                    type:'',
                    config: '',
                    enabled:true
                }
                this.ruleFormconfig='';
                this.ruleFormtype='';
            },
            asyncOK () {
            	this.modal1 = false;
            },
            //获取数据源
            getDatalist() {
                var _this = this;
                var path='storage/list';
                zmitiUtil.Ajax(path).then(res => {
                    var data = res.data;               
                    if (data) {
                        console.log(data,'获取数据源')
                        _this.httpData=data;
                        _this.dataCount=data.length;
                    }
                    console.log(res,'res');
                }).catch((error) => {
                    console.log(error,'error');
                });
            },
            saveStorage() {//添加数据            
                var _this = this;                
                var path='storage/add';
                var postData = {//参数
                  name: this.ruleForm.name,
                  type:this.ruleForm.type,
                  config:this.ruleForm.config,//JSON.parse(this.ruleForm.config),
                  enabled:this.ruleForm.enabled
                }
                
                this.$refs['ruleForm'].validate((valid) => {
                    if (valid) {
                        console.log(postData,'postData')
                        zmitiUtil.Ajax(path,postData).then(res => {
                            var data = res.data;               
                            if (data.code==1) {
                                console.log(data,'添加成功') ;
                                _this.modal1=false;
                                _this.getDatalist();   
                                _this.$Message.success('添加成功!');                    
                            }else{
                                console.log(res.data,'错误');
                                _this.$Message.error(data.result);
                            }
                        })

                    } else {
                        this.$Message.error('请填写完整');
                    }

                })
            },
            delStorage(name){//删除数据源
                var _this = this;                
                var path='storage/delete';
                var postData = {//参数
                    name
                }
                zmitiUtil.Ajax(path,postData).then(res => {
                    var data = res.data;               
                    if (data.result=='Success') {
                        _this.getDatalist();   
                        _this.$Message.success('删除成功!');                    
                    }else{
                        console.log(res.data,'错误');
                        _this.$Message.error(data.result);
                    }
                }).catch((error) => {
                    console.log(error,'error');
                });
            },
            checkStorage(params,enabled){//启用状态
                var _this = this;                
                var path='storage/enable';
                var postData = {//参数
                	name:params.row.name,
                    enabled
                }
                zmitiUtil.Ajax(path,postData).then(res => {
                    var data = res.data;               
                    if (data.result=='Success') {
                        _this.httpData[params.index].config.enabled=enabled
                        _this.$Message.success('设置成功!');                 
                    }else{
                        console.log(res.data,'错误');
                        _this.$Message.error(data.result);
                    }
                }).catch((error) => {
                    console.log(error,'error');
                });
            },
            openDetail(name,viewtype){
                /*viewtype=0为查看name，viewtype=1为查看type*/
                viewtype==0?this.modal1=true:'';                             
            	var _this = this;
                var path='storage/detail/'+name;
                var postData = {}
                if(name){
                    if(viewtype==0){
                        /*根据name查看*/
                        postData.name=name;
                    }
                    zmitiUtil.Ajax(path,postData).then(res => {
                        var data = res.data;  
                        if(viewtype==0){
                            if(_this.modaltype!=1){
                                /*当为“查看”或“修改”数据源时填充ruleForm表单*/
                                _this.ruleForm=res.data;
                                _this.ruleForm.enabled=res.data.config.enabled
                            } 
                        }
                        /*填充config配置*/
                        _this.ruleFormconfig=data.config;
                        _this.ruleForm.config=JSON.stringify(data.config);
                        let configtype=JSON.parse(data.config);
                        _this.ruleForm.type=configtype.type;
                        console.log(_this.ruleForm,'_this.ruleForm');
                        
                    }).catch((error) => {
                        console.log(error,'error');
                    });
                }
            },
            viewtypeList(type){//查询数据源配置模板
                console.log(type,'选择的select');
                var _this = this;
                var path='storage/config';
                var postData = {
                    type
                }
                if(type){
                    zmitiUtil.Ajax(path,postData).then(res => {
                        var data = res.data;
                        /*填充config配置*/
                        _this.ruleFormconfig=data;
                        _this.ruleForm.config=JSON.stringify(data);
                    }).catch((error) => {
                        console.log(error,'error');
                    });
                }
            },
            selectypeHandle(val){
                /*根据type查看详情*/
                var _this = this;
                console.log(val,'选择的select');
                _this.openDetail(val,1);
            }
        },
        created() {

        }
    }
</script>